package linkedlist;


public class Josepfu {
    public static void main(String[] args) {

        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addBoy(20);
        circleSingleLinkedList.showBoy();

        circleSingleLinkedList.countBoy(1,2,20);
    }
}

//创建一个环形的单向链表
class CircleSingleLinkedList{
    private Boy first = null;

    /**
     *
     * @param nums
     */
    public void addBoy(int nums){
        if (nums < 1){
            System.out.println("nums的值不正确");
            return;
        }
        Boy curBoy = null;
        for (int i=1; i <= nums; i++){
            Boy boy = new Boy(i);
            if (i == 1){
                first = boy;
                first.setNext(first);
                curBoy = first;
            }else{
                curBoy.setNext(boy);
                boy.setNext(first);
                curBoy = boy;
            }
        }
    }

    //遍历当前的环形链表
    public void showBoy(){
        if (first == null){
            System.out.println("空");
            return;
        }
        Boy curBoy = first;
        while(true){
            System.out.println("小孩的编号：" + curBoy.getNo());
            if (curBoy.getNext() == first){
                break;
            }
            curBoy = curBoy.getNext();
        }
    }

    //根据用户的输入，计算出小孩的出圈顺序

    /**
     *
     * @param startNo 表示第几个小孩开始数数
     * @param countNum 表示数几下
     * @param nums  表示最初有多少小孩在圈中
     */
    public void countBoy(int startNo, int countNum, int nums){
        //先对数据检验
        if (first == null || startNo < 1 || startNo > nums){
            System.out.println("参数有误");
            return;
        }
        Boy helper = first;
        //创建一个辅助指针helper，事先指向环形链表的最后这个节点
        while(helper.getNext() != first){
            helper = helper.getNext();
        }
        //小孩报数前，先让first和helper移动countNum-1次
        for (int i = 0; i < startNo - 1; i++){
            first = first.getNext();
            helper = helper.getNext();
        }

        while(helper != first){
            for (int i = 0; i <countNum -1; i++){
                first = first.getNext();
                helper = helper.getNext();
            }
            System.out.println("出圈的小孩编号是：" + first.getNo());
            first = first.getNext();
            helper.setNext(first);
        }
        System.out.println("最后留在圈中的小孩编号是：" + helper.getNo());
    }

}

class Boy{
    private int no;
    private Boy next;
    public Boy(int no){
        this.no = no;
    }
    public int getNo(){
        return no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy next) {
        this.next = next;
    }
}